import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/storage'

// 引入一级路由 --- 以下为路由懒加载写法
const Layout = () => import('@/views/Layout.vue')
const Detail = () => import('@/views/Detail.vue')
const Login = () => import('@/views/Login.vue')
const Register = () => import('@/views/Register.vue')

// 二级路由
const Article = () => import('@/views/Article.vue')
const Collect = () => import('@/views/Collect.vue')
const Like = () => import('@/views/Like.vue')
const User = () => import('@/views/User.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/article', // 1、重定向
      children: [
        { path: '/article', component: Article },
        { path: '/collect', component: Collect },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    },
    { path: '/detail/:id', component: Detail },
    { path: '/login', component: Login },
    { path: '/register', component: Register }
  ]
})
// 添加导航守卫
// 导航守卫：路由跳转进入页面之前会触发的一个函数
// 实现页面访问权限
router.beforeEach((to, from, next) => {
  // to: 去哪里 -- 到哪里去的路由信息对象
  // to.path ==> 去哪里的路由路径
  // from 从哪里来，从你哪里来的路由信息对象
  // next 放行函数 -- 是否放行
  // console.log(to)
  // console.log(from)
  // console.log(next)
  // next()
  const token = getItem()
  if (token) {
    // token存在 则直接放行
    next()
  } else {
    // token不存在 则判断跳转页面是否可放行
    const whiteArr = ['/login', '/register']
    if (whiteArr.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
